package demo1;


import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.ParseException;
import java.util.Properties;

/**
 * @description: JDBC封装类
 * @author: apple
 * @date:  2022/1/9 4:58 下午
 * @version 1.0
 **/
public class JDBCUtil {

    public static Connection getConnection() throws SQLException, IOException {
        final InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        // 获取链接
        String url = (String) properties.get("url");
        String userName = (String) properties.get("uname");
        String pwd = (String) properties.get("pwd");
        final Connection connection = DriverManager.getConnection(url, userName, pwd);
        return  connection;
    }


    public static void closeConnection(Connection conn, Statement ps) throws SQLException, IOException {

       closeConnection(conn,ps,null);
    }

    public static void closeConnection(Connection conn, Statement ps,ResultSet rs) throws SQLException, IOException {

        if (rs != null) {
            rs.close();
            System.out.println("ResultSet关闭成功");
        }
        if (ps != null) {
            ps.close();
            System.out.println("Statement关闭成功");
        }
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
            System.out.println("Connection关闭成功");
        }

    }

    public static void update( String sql , Object...params) throws SQLException, ParseException, IOException {
        final Connection connection = JDBCUtil.getConnection();
        final PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1, params[i]);
        }
        preparedStatement.execute();
        JDBCUtil.closeConnection(connection,preparedStatement);
        System.out.println("close...");
    }
}
